<?php
namespace app\admin\model;

use think\Model;

class Admin extends Model
{
    protected $name = 'users';       // 对应数据表（管理员/用户共用表）
    protected $hidden = ['password'];// 默认隐藏密码字段

    /**
     * 获取管理员列表（仅查role≥1的管理员，排除普通用户）
     */
    public static function getList(int $page, int $limit)
    {
        return self::where('role', '>=', 1)
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $limit, // 每页数量
                'page'      => $page,  // 当前页码
                'simple'    => false   // 是否简洁模式（false 会返回总条数等完整信息）
            ]);
    }

    /**
     * 根据ID查找管理员
     */
    public static function findById(int $id)
    {
        return self::find($id);
    }

    /**
     * 检查用户名是否存在（排除指定ID）
     */
    public static function checkUsernameExists(string $username, int $excludeId = 0)
    {
        $query = self::where('username', trim($username));
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        return $query->find();
    }

    /**
     * 检查邮箱是否存在（排除指定ID）
     */
    public static function checkEmailExists(string $email, int $excludeId = 0)
    {
        $query = self::where('email', trim($email));
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        return $query->find();
    }

    /**
     * 检查手机号是否存在（排除指定ID）
     */
    public static function checkPhoneExists(string $phone, int $excludeId = 0)
    {
        $query = self::where('phone', trim($phone));
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        return $query->find();
    }

    /**
     * 更新管理员信息
     */
    public function updateAdminInfo(array $data)
    {
        // 更新字段
        if (isset($data['username'])) {
            $this->username = trim($data['username']);
        }
        if (isset($data['password']) && !empty($data['password'])) {
            $this->password = password_hash(trim($data['password']), PASSWORD_DEFAULT);
        }
        if (isset($data['email'])) {
            $this->email = $data['email'];
        }
        if (isset($data['phone'])) {
            $this->phone = $data['phone'];
        }
        if (isset($data['avatar'])) {
            $this->avatar = trim($data['avatar']);
        }
        if (isset($data['role'])) {
            $this->role = $data['role'];
        }
        if (isset($data['status'])) {
            $this->status = $data['status'];
        }

        return $this->save();
    }

    /**
     * 删除管理员
     */
    public function deleteAdmin()
    {
        return $this->delete();
    }
}